import os
import time
from selenium.webdriver.support.wait import WebDriverWait

from common.recordlog import logs
from conf.setting import DIR_BASE


class Base:

    # 初始化方法
    def __init__(self, driver):
        logs.info("正在初始化，driver对象：{}".format(driver))
        self.driver = driver

    # 查找元素方法
    def base_find(self, loc, timeout=30, poll=1):
        logs.info("正在查找元素：{}".format(loc))
        data = WebDriverWait(self.driver, timeout, poll).until(lambda x: x.find_element(*loc))
        return data

    # 隐式等待
    def base_find_byimp(self, loc, timeout=30):
        logs.info("正在查找元素：{}".format(loc))
        # 设置隐式等待时间
        self.driver.implicitly_wait(timeout)
        try:
            data = self.driver.find_element(*loc)
            return data
        except Exception as e:
            logs.error(f"查找元素失败: {e}")
            raise
        finally:
            # 将隐式等待时间重置为默认值（通常是0）
            self.driver.implicitly_wait(0)



    # 点击方法
    def base_click(self, loc):
        try:
            logs.info("正调用点击元素：{}".format(loc))
            self.base_find(loc).click()
        except Exception as e:
            logs.error(f"点击元素异常{loc}  异常：{e}")


    # 输入方法
    def base_input(self, loc, value):
        logs.info("正调用输入元素方法：{} 输入内容：{}".format(loc,value))
        # 获取元素
        el = self.base_find(loc)
        # 清空
        el.clear()
        # 输入
        el.send_keys(value)

    # 获取文本方法
    def base_get_text(self, loc):
        logs.info("正调用获取元素信息方法：{}".format(loc))
        ele = self.base_find(loc)
        data = ele.text
        return data

    # 截图方法
    def base_get_img(self):
        logs.info("正调用截图方法")
        img_path = DIR_BASE + os.sep + "img" + os.sep + "{}.png".format(time.strftime("%Y%m%d%H%M%S"))
        self.driver.get_screenshot_as_file(img_path)

    # 切换iframe
    def base_switch_frame(self, loc):
        logs.info("正在调用切换frame方法，切换对象：{}".format(loc))
        # 获取元素
        el = self.base_find(loc)
        logs.info(f"el:{el}")
        # 执行切换
        try:
            self.driver.switch_to.frame(el)
            logs.info("切换iframe成功")
        except Exception as e:
            logs.error(f"切换iframe失败 异常：{e}")

    # 恢复frame
    def base_default_frame(self):
        self.driver.switch_to.default_content()


